package com.central;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import org.json.JSONException;
import org.json.JSONObject;

public class ServerThreadCentral implements Runnable  {
	private Socket soc;
	private int portServeur;
	private PrintWriter out;
	private BufferedReader in;
	private int idProd;
	private int quantity;
	private int codeLivraison; 
	
	//public ServerThreadCentral(int port){ //port = codeLivraison
	//public ServerThreadCentral(JSONObject json){ //port = codeLivraison
	public ServerThreadCentral(int idProd,int quantity, int codeLivraison){ //port = codeLivraison
		//this.portServeur=json.getInt("codeLivraison");
		this.idProd = idProd;
		this.quantity = quantity;
		this.codeLivraison = codeLivraison;
		//System.out.println("########### stc "+port);
	}
	public void run() {
//		System.out.println("########### RUN ServCentThread");
//		Json2Sql j2s = new Json2Sql();
//		Processing process = new Processing();
//		try{
//			Central central = new Central(portServeur);
//			System.out.println("########### run thread central");
//			socket = new Socket();
//			out = new PrintWriter(socket.getOutputStream(), true);
//			InputStreamReader isr=new InputStreamReader(socket.getInputStream());
//			in = new BufferedReader(isr);
//			while(true)
//			{
//				while(!in.ready());
//				String line = in.readLine();
//				JSONObject jsonO = new JSONObject(line);
//			}
//		}catch(Exception e){
//			e.printStackTrace();
//			System.err.println("Thread : "+e.getMessage());
////		}
//		int port = 10001;
		int pu = 10;
		System.out.println("###########ServerThreadCentral => idProd "+idProd);
		//Central central = new Central(idProd,quantity,codeLivraison,pu);
		String ip = "127.0.0.1";
		JSONObject jso = new JSONObject();
		try {
			jso.put("message", "book");
			jso.put("productId", idProd);
			jso.put("wantedQty", quantity);
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		
		try 
		{
//			Socket soc = new Socket(ip,port);		
			soc = new Socket(ip,codeLivraison);			
			InputStreamReader isr = new InputStreamReader(soc.getInputStream());
			BufferedReader in = new BufferedReader(isr);
			PrintWriter out = new PrintWriter(soc.getOutputStream(),true);
			out.println(jso);
			while(!in.ready());
			String line = in.readLine();
			System.out.println("############## line = "+line);
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
		
	}

}
